package com.example.stray_animal_management_system.commonu.controller;

import com.example.stray_animal_management_system.commonu.service.RescueInfoService;
import com.example.stray_animal_management_system.entity.RescueInfo;
import com.example.stray_animal_management_system.util.CodeGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author: panpan
 * @time: 2025/10/26
 */
@RestController
@RequestMapping("/api/rescue")
@CrossOrigin
public class RescueInfoController {

    @Autowired
    private RescueInfoService rescueInfoService;

    /**
     * 用户上报救助
     */
    @PostMapping("/report")
    public Map<String, Object> reportRescue(@RequestBody RescueInfo rescueInfo) {
        Map<String, Object> res = new HashMap<>();

        rescueInfo.setReportTime(LocalDateTime.now());
        rescueInfo.setStatus(0);
        rescueInfo.setRescueCode(CodeGeneratorUtil.generateRescueCode());

        boolean saved = rescueInfoService.save(rescueInfo);
        if (saved) {
            res.put("code", 200);
            res.put("msg", "救助信息上报成功");
            res.put("rescueCode", rescueInfo.getRescueCode());
            res.put("timestamp", System.currentTimeMillis());
        } else {
            res.put("code", 500);
            res.put("msg", "上报失败");
        }
        return res;
    }

    /**
     *  图片上传接口
     */
    @PostMapping("/uploadPhoto")
    public Map<String, Object> uploadPhoto(@RequestParam("file") MultipartFile file) {
        Map<String, Object> res = new HashMap<>();
        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        String uploadDir = System.getProperty("user.dir") + "/uploads/rescue_photos/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir + fileName);

        try {
            file.transferTo(dest);
            String fileUrl = "http://localhost:8080/uploads/rescue_photos/" + fileName;
            res.put("code", 200);
            res.put("msg", "上传成功");
            res.put("url", fileUrl);
        } catch (IOException e) {
            res.put("code", 500);
            res.put("msg", "上传失败：" + e.getMessage());
        }

        return res;
    }

    /**
     * 查询当前用户的所有救助记录
     */
    @GetMapping("/user/{userId}")
    public Map<String, Object> listByUser(@PathVariable Integer userId) {
        Map<String, Object> res = new HashMap<>();

        List<RescueInfo> list = rescueInfoService.lambdaQuery()
                .eq(RescueInfo::getReporterId, userId)
                .list();

        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", list);
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /**
     * 修改自己的救助记录
     */
    @PutMapping("/update")
    public Map<String, Object> updateMyReport(@RequestBody RescueInfo rescueInfo) {
        Map<String, Object> res = new HashMap<>();

        RescueInfo dbInfo = rescueInfoService.getById(rescueInfo.getId());
        if (dbInfo == null) {
            res.put("code", 404);
            res.put("msg", "记录不存在");
            return res;
        }

        // 验证是否本人操作
        if (!dbInfo.getReporterId().equals(rescueInfo.getReporterId())) {
            res.put("code", 403);
            res.put("msg", "不能修改他人的记录");
            return res;
        }

        boolean updated = rescueInfoService.updateById(rescueInfo);
        res.put("code", updated ? 200 : 500);
        res.put("msg", updated ? "修改成功" : "修改失败");
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /**
     *  删除自己的救助记录
     */
    @DeleteMapping("/delete/{id}/{userId}")
    public Map<String, Object> deleteMyReport(@PathVariable Integer id, @PathVariable Integer userId) {
        Map<String, Object> res = new HashMap<>();

        RescueInfo dbInfo = rescueInfoService.getById(id);
        if (dbInfo == null) {
            res.put("code", 404);
            res.put("msg", "记录不存在");
            return res;
        }

        // 验证是否本人操作
        if (!dbInfo.getReporterId().equals(userId)) {
            res.put("code", 403);
            res.put("msg", "不能删除他人的记录");
            return res;
        }

        boolean removed = rescueInfoService.removeById(id);
        res.put("code", removed ? 200 : 500);
        res.put("msg", removed ? "删除成功" : "删除失败");
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }
}